package hr.fer.zemris.revhttp.gateway.resources;

import hr.fer.zemris.revhttp.gateway.websockets.ServerInterfaceServlet.ServerInterfaceSocket;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tomek
 */
public class GatewayResources {
	private static final Map<Object, Object> resourceUUIDs = new HashMap<Object, Object>();
	private static final Map<Object, ServerInterfaceSocket> resourceSockets = new HashMap<Object, ServerInterfaceSocket>();

	/**
	 * @param regex
	 * @return uuid of the registered resource if it doesn't exist yet, null
	 *         otherwise
	 */
	public static String registerResourceRegex(String regex) {
		if (resourceUUIDs.containsKey(regex))
			return null;
		String uuid = generateUUID();
		resourceUUIDs.put(regex, uuid);
		return uuid;
	}

	/**
	 * @param regex
	 */
	public static void unregisterResourceRegex(String regex) {
		if (!resourceUUIDs.containsKey(regex))
			return;
		resourceUUIDs.remove(regex);
	}

	public static Object getResourceUUID(Object regex) {
		return resourceUUIDs.get(regex);
	}

	/**
	 * Checks if uuid coresponds to the given path regex
	 * 
	 * @param regex
	 * @param uuid
	 * @return true if satisfied, false otherwise
	 */
	public static boolean isValidUUID(Object regex, Object uuid) {
		if (uuid == null || regex == null)
			return false;
		return uuid.equals(resourceUUIDs.get(regex));
	}

	/**
	 * @param regex
	 * @param socket
	 */
	public static void addResource(Object regex, ServerInterfaceSocket socket) {
		resourceSockets.put(regex, socket);
	}

	/**
	 * @param regex
	 * @return if removed
	 */
	public static boolean removeResource(Object regex) {
		if (!resourceSockets.containsKey(regex))
			return false;
		resourceSockets.remove(regex);
		return true;
	}

	public static String generateUUID() {
		char[] uuid = new char[36];
		char[] nineteen = new String("89AB").toCharArray();
		char[] hex = new String("0123456789ABCDEF").toCharArray();
		for (int i = 0; i < 36; i++) {
			uuid[i] = hex[(int) (Math.floor(Math.random() * 16))];
		}
		uuid[14] = '4';
		uuid[19] = nineteen[(int) (Math.floor(Math.random() * 4))];
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';

		return new String(uuid);
	}

	/**
	 * @param requestId
	 * @param contextPath
	 * @return success?
	 */
	public static boolean relay(String requestId, String contextPath) {
		ServerInterfaceSocket socket = resourceSockets.get(contextPath);
		if (socket != null) {
			resourceSockets.get(contextPath).relayRequest(requestId,
					contextPath);
			return true;
		} else
			return false;
	}
}
